package controller

import (
	"bubble/model"
	"github.com/gin-gonic/gin"
	"net/http"
)

//并不是前后分离，相当于thymeleaf
func IndexHandler(c *gin.Context) {
	c.HTML(http.StatusOK, "index.html", "nil")
}
//这里的c是context，获取数据返回的json数据，左边跟地址，右边跟数据
func CreateTodo(c *gin.Context)  {
	//c中包含请求体
	var todo model.Todo
	c.Bind(&todo)
	//2.存入数据库
	err := model.CreateTodo(&todo)
	if err != nil{
		c.JSON(http.StatusNotFound,gin.H{"error":err.Error(),"message":"错误"})
	}else {
		c.JSON(http.StatusOK,todo)
	}
}

func GetTodoList(c *gin.Context) {
	todoList, err := model.GetAllTodo()
	if err !=nil {
		c.JSON(http.StatusNotFound,gin.H{"error":err.Error(),"message":"错误"})
	}else {
		c.JSON(http.StatusOK,todoList)
	}
}

func UpdateTodo(c *gin.Context) {
	id, ok := c.Params.Get("id")
	if !ok{
		c.JSON(http.StatusOK, gin.H{"error": "无效的id"})
		return
	}
	todo, err := model.GetTodo(id)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{"error": err.Error()})
		return
	}
	c.BindJSON(&todo)
	if err = model.UpdateTodo(todo); err != nil {
		c.JSON(http.StatusOK, gin.H{"error": err.Error()})
	} else {
		c.JSON(http.StatusOK, todo)
	}
}

func DeleteATodo(c *gin.Context) {
	id, ok := c.Params.Get("id")
	if !ok {
		c.JSON(http.StatusOK, gin.H{"error": "无效的id"})
		return
	}
	if err := model.DeleteATodo(id); err != nil {
		c.JSON(http.StatusOK, gin.H{"error": err.Error()})
	} else {
		c.JSON(http.StatusOK, gin.H{id: "deleted"})
	}
}


